<?php
# 文件名称:database.model.php
# MetInfo在线反馈系统 
# Copyright (C) 长沙米拓信息技术有限公司 (http://www.metinfo.cn). All rights reserved.
class databaseModel extends C_model {
	var $_records = array();
	
    function databaseModel()
    {
        parent::C_model();
    }
	//记录集
	function getItems()
	{
		if (!empty( $this->_data ))
		{
			return $this->_data;
		}
		$SYS =&get_instance();
		$this->_data = $this->_db->getTableList();
		//数据集
		foreach($this->_data as $key=>$val)
        {			
			$count = $this->_db->getone("SELECT count(*) as number FROM $val WHERE 1");
			$this->_records[$key] = $count;
        }
		
		return $this->_data;
	}
	function getRecords()
	{
		return $this->_records;
	}
	//导出数据
	function sql_dumptable($table, $startfrom = 0)
	{
		$SYS = &get_instance();
		$db = $this->_db;
    	$tabledump = '';
		
    	if(!$startfrom)
    	{
			$tabledump = "DROP TABLE IF EXISTS $table;\n";
			$db->setQuery("SHOW CREATE TABLE $table");
			$create = $db->loadRow();
			$tabledump .= $create[1].";\n\n";
		}		
    	$db->setQuery("SELECT * FROM $table");
		$cur=$db->query();
		$numfields = $db->getNumFields();
		//相应SQL语句
		while ($row = $db->loadRow_s($cur))
		{				
			$comma = "";
			$tabledump .= "INSERT INTO $table VALUES(";
			for($i = 0; $i < $numfields; $i++)
			{
				$tabledump .= $comma."'".mysql_escape_string($row[$i])."'";
				$comma = ",";
			}				
			$tabledump .= ");\n";				
		}			
		mysql_free_result( $cur );
		
    	$tabledump .= "\n";
    	return $tabledump;
    }
	//还原时执行相应SQL语句
	function sql_execute($sql)
	{
		$db = $this->_db;
	    $sqls = $this->sql_split($sql);
		if(is_array($sqls))
	    {
			foreach($sqls as $sql)
			{
				if(trim($sql) != '') 
			{
				$db->setQuery($sql);
				$db->query();
			}
		}
		}
    	else
    	{
			$db->setQuery($sql);
    		$db->query();
    	}
		return true;
	}
	//SQL语句清理
	function sql_split($sql)
	{
		$db = $this->_db;
		if($db->getVersion() > '4.1')
		{
			$sql = preg_replace("/TYPE=(InnoDB|MyISAM)( DEFAULT CHARSET=[^; ]+)?/", "TYPE=\\1 DEFAULT CHARSET=utf8",$sql);
		}
		$sql = str_replace("\r", "\n", $sql);
    	$ret = array();
    	$num = 0;
    	$queriesarray = explode(";\n", trim($sql));
    	unset($sql);
		foreach($queriesarray as $query)
		{
			$ret[$num] = '';
			$queries = explode("\n", trim($query));
			$queries = array_filter($queries);
			foreach($queries as $query)
			{
				$str1 = substr($query, 0, 1);
				if($str1 != '#' && $str1 != '-') $ret[$num] .= $query;
			}
			$num++;
		}
		return($ret);
	}
}
# 本程序是一个开源系统,使用时请你仔细阅读使用协议,商业用途请自觉购买商业授权.
# Copyright (C) 长沙米拓信息技术有限公司 (http://www.metinfo.cn). All rights reserved.
?>